package com.tct.worktimeboard.feishu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Huhailong
 * @Description 对接飞书接口
 * @Date 2021/5/10.
 */
@Slf4j
@Component
public class FeiShuUtil {
    @Value("${feishu.app-id}")
    private String appId;
    @Value("${feishu.app-secret}")
    private String appSecret;
    @Value("${feishu.api-url}")
    private String appUrl;
    @Autowired
    RestTemplate restTemplate;

    /**
     * 根据手机号查询用户信息
     * @param tel 手机号
     * @return 返回用户open_id和user_id
     */
    public Map<String,String> getUserInfo(String tel){
        String tenantAccessToken = getTenantAccessToken();
        String requestUrl = appUrl+"user/v1/batch_get_id?mobiles="+tel;
        HttpEntity<String> request = new HttpEntity<>(null,makeHeaders(tenantAccessToken));
        String userInfo = restTemplate.exchange(requestUrl, HttpMethod.GET, request, String.class).getBody();
        JSONObject object = JSONObject.parseObject(userInfo);
        Integer status = object.getInteger("code");
        if(status!=0){
            log.error("飞书获取用户信息接口报错，报错编号：{}，报错内容：{}",status,object.getString("msg"));
            return null;
        }
        int size = object.getJSONObject("data").getJSONArray("mobiles_not_exist").size();
        if(size!=0){
            log.error("{}，该手机号不存在对应用户",tel);
            return null;
        }
        JSONArray jsonArray = object.getJSONObject("data").getJSONObject("mobile_users").getJSONArray(tel);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("openId",jsonObject.getString("open_id"));
        resultMap.put("userId",jsonObject.getString("user_id"));
        log.info("get user info {}",JSONObject.toJSONString(resultMap));
        return resultMap;
    }

    public List<String> getUserInfoList(List<String> tels){
        log.info("tels:{}",tels);
        String tenantAccessToken = getTenantAccessToken();
        StringBuilder param = new StringBuilder();
        tels.forEach(tel->{
            param.append("mobiles=").append(tel).append("&");
        });
        String requestUrl = appUrl+"user/v1/batch_get_id?"+param;
        HttpEntity<String> request = new HttpEntity<>(null,makeHeaders(tenantAccessToken));
        String userInfo = restTemplate.exchange(requestUrl, HttpMethod.GET, request, String.class).getBody();
        JSONObject object = JSONObject.parseObject(userInfo);
        Integer status = object.getInteger("code");
        if(status!=0){
            log.error("飞书获取用户信息接口报错，报错编号：{}，报错内容：{}",status,object.getString("msg"));
            return null;
        }
        JSONArray noUserTels = object.getJSONObject("data").getJSONArray("mobiles_not_exist");
        log.info("没有对应用户的手机号：{}",noUserTels);
        String dataStr = object.getJSONObject("data").getString("mobile_users");
        Map<String, List<Map<String, String>>> stringListMap = JSONObject.parseObject(dataStr, new TypeReference<Map<String, List<Map<String, String>>>>() {
        });
        List<String> openIdList = stringListMap.values().stream().map(item -> item.get(0).get("open_id")).collect(Collectors.toList());
        log.info("openIdList:{}",openIdList);
        return openIdList;
    }

    public String getTenantAccessToken(){
        String requestUrl = appUrl+"auth/v3/tenant_access_token/internal/";
        Map<String,Object> requestBody = new HashMap<>();
        requestBody.put("app_id",appId);
        requestBody.put("app_secret",appSecret);
        HttpEntity<String> request = new HttpEntity<>(JSONObject.toJSONString(requestBody),makeHeaders(null));
        String token = restTemplate.postForEntity(requestUrl, request, String.class).getBody();
        JSONObject object = JSONObject.parseObject(token);
        log.info("tenant_access_token:{}",object.getString("tenant_access_token"));
        return object.getString("tenant_access_token");
    }

    public HttpHeaders makeHeaders(String token){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if(token!=null){
            headers.add(HttpHeaders.AUTHORIZATION,"Bearer "+token);
        }
        return headers;
    }


}
